<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />

<title>Prototype &middot; Design Patterns Revisited &middot; Game Programming Patterns</title>

<!-- Tell mobile browsers we're optimized for them and they don't need to crop
     the viewport. -->
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="style.css" />
<link href="http://fonts.googleapis.com/css?family=Merriweather:400,400italic,700,700italic|Source+Code+Pro|Source+Sans+Pro:200,300,400,600,400italic,600italic|Rock+Salt" rel="stylesheet" type="text/css">
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-42804721-1', 'gameprogrammingpatterns.com');
  ga('send', 'pageview');
</script>
<script src="jquery-1.10.1.min.js"></script>
<script src="script.js"></script>
</head>
<body id="top">
<div class="page sidebar">
<div class="content">
<nav class="top">
  <span class="prev">&larr; <a href="observer.html">Previous Chapter</a></span>
  <span class="next"><a href="singleton.html">Next Chapter</a> &rarr;</span>
  <span class="toc">&equiv; <a href="/">The Book</a></span>
</nav>
<h1>Prototype</h1>
<h1 class="book"><a href="/">Game Programming Patterns</a><span class="section"><a href="design-patterns-revisited.html">Design Patterns Revisited</a></span></h1>
<p>The first time I heard the word &#8220;prototype&#8221; was in <em>Design Patterns</em>. Today, it
seems like everyone is saying it, but it turns out they aren&#8217;t talking about the
<a href="http://en.wikipedia.org/wiki/Prototype_pattern"
class="gof-pattern">design pattern</a>. We&#8217;ll cover that here, but I&#8217;ll also
show you other, more interesting places where the term &#8220;prototype&#8221; and the
concepts behind it have popped up. But first, let&#8217;s revisit the <span
name="original">original</span> pattern.</p>
<aside name="original">

<p>I don&#8217;t say &#8220;original&#8221; lightly here. <em>Design Patterns</em> cites Ivan Sutherland&#8217;s
legendary <a href="http://en.wikipedia.org/wiki/Sketchpad">Sketchpad</a> project in <em>1963</em>
as one of the first examples of this pattern in the wild. While everyone else
was listening to Dylan and the Beatles, Sutherland was busy just, you know,
inventing the basic concepts of CAD, interactive graphics, and object-oriented
programming.</p>
<p>Watch <a href="http://www.youtube.com/watch?v=USyoT_Ha_bA">the demo</a> and prepare to be
blown away.</p>
</aside>

<h2><a href="#the-prototype-design-pattern" name="the-prototype-design-pattern">The Prototype Design Pattern</a></h2>
<p>Pretend we&#8217;re making a game in the style of Gauntlet. We&#8217;ve got creatures and
fiends swarming around the hero, vying for their share of his flesh. These
unsavory dinner companions enter the arena by way of &#8220;spawners&#8221;, and there is a
different spawner for each kind of enemy.</p>
<p>For the sake of this example, let&#8217;s say we have different classes for each kind
of monster in the game&#8202;&mdash;&#8202;<code>Ghost</code>, <code>Demon</code>, <code>Sorcerer</code>, etc., like:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Monster</span>
<span class="p">{</span>
  <span class="c1">// Stuff...</span>
<span class="p">};</span>

<span class="k">class</span> <span class="nc">Ghost</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Monster</span> <span class="p">{};</span>
<span class="k">class</span> <span class="nc">Demon</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Monster</span> <span class="p">{};</span>
<span class="k">class</span> <span class="nc">Sorcerer</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Monster</span> <span class="p">{};</span>
</pre></div>


<p>A spawner constructs instances of one particular monster type. To support every
monster in the game, we <em>could</em> brute-force it by having a spawner class for
each monster class, leading to a parallel class hierarchy:</p>
<p><span name="inherits-arrow"></span></p>
<p><img src="images/prototype-hierarchies.png" alt="Parallel class hierarchies. Ghost, Demon, and Sorceror all inherit from Monster. GhostSpawner, DemonSpawner, and SorcerorSpawner inherit from Spawner." /></p>
<aside name="inherits-arrow">

<p>I had to dig up a dusty UML book to make this diagram. The <img
src="images/arrow-inherits.png" class="arrow" alt="A UML arrow." /> means &#8220;inherits from&#8221;.</p>
</aside>

<p>Implementing it would look like this:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Spawner</span>
<span class="p">{</span>
<span class="nl">public:</span>
  <span class="k">virtual</span> <span class="o">~</span><span class="n">Spawner</span><span class="p">()</span> <span class="p">{}</span>
  <span class="k">virtual</span> <span class="n">Monster</span><span class="o">*</span> <span class="n">spawnMonster</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">};</span>

<span class="k">class</span> <span class="nc">GhostSpawner</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Spawner</span>
<span class="p">{</span>
<span class="nl">public:</span>
  <span class="k">virtual</span> <span class="n">Monster</span><span class="o">*</span> <span class="n">spawnMonster</span><span class="p">()</span>
  <span class="p">{</span>
    <span class="k">return</span> <span class="k">new</span> <span class="n">Ghost</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">};</span>

<span class="k">class</span> <span class="nc">DemonSpawner</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Spawner</span>
<span class="p">{</span>
<span class="nl">public:</span>
  <span class="k">virtual</span> <span class="n">Monster</span><span class="o">*</span> <span class="n">spawnMonster</span><span class="p">()</span>
  <span class="p">{</span>
    <span class="k">return</span> <span class="k">new</span> <span class="n">Demon</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">};</span>

<span class="c1">// You get the idea...</span>
</pre></div>


<p>Unless you get paid by the line of code, this is obviously not a fun way
to hack this together. Lots of classes, lots of boilerplate, lots of redundancy,
lots of duplication, lots of repeating myself&#8230;</p>
<p>The Prototype pattern offers a solution. The key idea is that <em>an object can
spawn other objects similar to itself</em>. If you have one ghost, you can make more
ghosts from it. If you have a demon, you can make other demons. Any monster can
be treated as a <em>prototypal</em> monster used to generate other versions of
itself.</p>
<p>To implement this, we give our base class, <code>Monster</code>, an abstract <code>clone()</code>
method:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Monster</span>
<span class="p">{</span>
<span class="nl">public:</span>
  <span class="k">virtual</span> <span class="o">~</span><span class="n">Monster</span><span class="p">()</span> <span class="p">{}</span>
  <span class="k">virtual</span> <span class="n">Monster</span><span class="o">*</span> <span class="n">clone</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

  <span class="c1">// Other stuff...</span>
<span class="p">};</span>
</pre></div>


<p>Each monster subclass provides an implementation that returns a new object
identical in class and state to itself. For example:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Ghost</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Monster</span> <span class="p">{</span>
<span class="nl">public:</span>
  <span class="n">Ghost</span><span class="p">(</span><span class="kt">int</span> <span class="n">health</span><span class="p">,</span> <span class="kt">int</span> <span class="n">speed</span><span class="p">)</span>
  <span class="o">:</span> <span class="n">health_</span><span class="p">(</span><span class="n">health</span><span class="p">),</span>
    <span class="n">speed_</span><span class="p">(</span><span class="n">speed</span><span class="p">)</span>
  <span class="p">{}</span>

  <span class="k">virtual</span> <span class="n">Monster</span><span class="o">*</span> <span class="n">clone</span><span class="p">()</span>
  <span class="p">{</span>
    <span class="k">return</span> <span class="k">new</span> <span class="n">Ghost</span><span class="p">(</span><span class="n">health_</span><span class="p">,</span> <span class="n">speed_</span><span class="p">);</span>
  <span class="p">}</span>

<span class="nl">private:</span>
  <span class="kt">int</span> <span class="n">health_</span><span class="p">;</span>
  <span class="kt">int</span> <span class="n">speed_</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>


<p>Once all our monsters support that, we no longer need a spawner class for each
monster class. Instead, we define a single one:</p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Spawner</span>
<span class="p">{</span>
<span class="nl">public:</span>
  <span class="n">Spawner</span><span class="p">(</span><span class="n">Monster</span><span class="o">*</span> <span class="n">prototype</span><span class="p">)</span>
  <span class="o">:</span> <span class="n">prototype_</span><span class="p">(</span><span class="n">prototype</span><span class="p">)</span>
  <span class="p">{}</span>

  <span class="n">Monster</span><span class="o">*</span> <span class="n">spawnMonster</span><span class="p">()</span>
  <span class="p">{</span>
    <span class="k">return</span> <span class="n">prototype_</span><span class="o">-&gt;</span><span class="n">clone</span><span class="p">();</span>
  <span class="p">}</span>

<span class="nl">private:</span>
  <span class="n">Monster</span><span class="o">*</span> <span class="n">prototype_</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>


<p>It internally holds a monster, a hidden one whose sole purpose is to be used by
the spawner as a template to stamp out more monsters like it, sort of like a
queen bee who never leaves the hive.</p>
<p><img src="images/prototype-spawner.png" alt="A Spawner contains a prototype field referencing a Monster. It calls clone() on the prototype to create new monsters." /></p>
<p>To create a ghost spawner, we create a prototypal ghost instance and
then create a spawner holding that prototype:</p>
<div class="codehilite"><pre><span class="n">Monster</span><span class="o">*</span> <span class="n">ghostPrototype</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Ghost</span><span class="p">(</span><span class="mi">15</span><span class="p">,</span> <span class="mi">3</span><span class="p">);</span>
<span class="n">Spawner</span><span class="o">*</span> <span class="n">ghostSpawner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Spawner</span><span class="p">(</span><span class="n">ghostPrototype</span><span class="p">);</span>
</pre></div>


<p>One neat part about this pattern is that it doesn&#8217;t just clone the <em>class</em> of
the prototype, it clones its <em>state</em> too. This means we could make a spawner for
fast ghosts, weak ghosts, or slow ghosts just by creating an appropriate
prototype ghost.</p>
<p>I find something both elegant and yet surprising about this pattern. I can&#8217;t
imagine coming up with it myself, but I can&#8217;t imagine <em>not</em> knowing about it now
that I do.</p>
<h3><a href="#how-well-does-it-work" name="how-well-does-it-work">How well does it work?</a></h3>
<p>Well, we don&#8217;t have to create a separate spawner class for each monster, so
that&#8217;s good. But we <em>do</em> have to implement <code>clone()</code> in each monster class.
That&#8217;s just about as much code as the spawners.</p>
<p>There are also some nasty semantic ratholes when you sit down to try to write a
correct <code>clone()</code>. Does it do a deep clone or shallow one? In other words, if a
demon is holding a pitchfork, does cloning the demon clone the pitchfork too?</p>
<p>Also, not only does this not look like it&#8217;s saving us much code in this
contrived problem, there&#8217;s the fact that it&#8217;s a <em>contrived problem</em>. We had to
take as a given that we have separate classes for each monster. These days,
that&#8217;s definitely <em>not</em> the way most game engines roll.</p>
<p>Most of us learned the hard way that big class hierarchies like this are a pain
to manage, which is why we instead use patterns like <a href="component.html"
class="pattern">Component</a> and <a href="type-object.html"
class="pattern">Type Object</a> to model different kinds of entities without
enshrining each in its own class.</p>
<h3><a href="#spawn-functions" name="spawn-functions">Spawn functions</a></h3>
<p>Even if we do have different classes for each monster, there are other ways to
decorticate this <em>Felis catus</em>. Instead of making separate spawner <em>classes</em> for
each monster, we could make spawn <em>functions</em>, like so:</p>
<div class="codehilite"><pre><span class="n">Monster</span><span class="o">*</span> <span class="nf">spawnGhost</span><span class="p">()</span>
<span class="p">{</span>
  <span class="k">return</span> <span class="k">new</span> <span class="n">Ghost</span><span class="p">();</span>
<span class="p">}</span>
</pre></div>


<p>This is less boilerplate than rolling a whole class for constructing a monster
of some type. Then the one spawner class can simply store a function pointer:</p>
<div class="codehilite"><pre><span class="k">typedef</span> <span class="n">Monster</span><span class="o">*</span> <span class="p">(</span><span class="o">*</span><span class="n">SpawnCallback</span><span class="p">)();</span>

<span class="k">class</span> <span class="nc">Spawner</span>
<span class="p">{</span>
<span class="nl">public:</span>
  <span class="n">Spawner</span><span class="p">(</span><span class="n">SpawnCallback</span> <span class="n">spawn</span><span class="p">)</span>
  <span class="o">:</span> <span class="n">spawn_</span><span class="p">(</span><span class="n">spawn</span><span class="p">)</span>
  <span class="p">{}</span>

  <span class="n">Monster</span><span class="o">*</span> <span class="n">spawnMonster</span><span class="p">()</span>
  <span class="p">{</span>
    <span class="k">return</span> <span class="n">spawn_</span><span class="p">();</span>
  <span class="p">}</span>

<span class="nl">private:</span>
  <span class="n">SpawnCallback</span> <span class="n">spawn_</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>


<p>To create a spawner for ghosts, you do:</p>
<div class="codehilite"><pre><span class="n">Spawner</span><span class="o">*</span> <span class="n">ghostSpawner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Spawner</span><span class="p">(</span><span class="n">spawnGhost</span><span class="p">);</span>
</pre></div>


<h3><a href="#templates" name="templates">Templates</a></h3>
<p>By <span name="templates">now</span>, most C++ developers are familiar with
templates. Our spawner class needs to construct instances of some type, but we
don&#8217;t want to hard code some specific monster class. The natural solution then
is to make it a <em>type parameter</em>, which templates let us do:</p>
<aside name="templates">

<p>I&#8217;m not sure if C++ programmers learned to love them or if templates just
scared some people completely away from C++. Either way, everyone I see using
C++ today uses templates too.</p>
</aside>

<p><span name="base"></span></p>
<div class="codehilite"><pre><span class="k">class</span> <span class="nc">Spawner</span>
<span class="p">{</span>
<span class="nl">public:</span>
  <span class="k">virtual</span> <span class="o">~</span><span class="n">Spawner</span><span class="p">()</span> <span class="p">{}</span>
  <span class="k">virtual</span> <span class="n">Monster</span><span class="o">*</span> <span class="n">spawnMonster</span><span class="p">()</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">};</span>

<span class="k">template</span> <span class="o">&lt;</span><span class="k">class</span> <span class="nc">T</span><span class="o">&gt;</span>
<span class="k">class</span> <span class="nc">SpawnerFor</span> <span class="o">:</span> <span class="k">public</span> <span class="n">Spawner</span>
<span class="p">{</span>
<span class="nl">public:</span>
  <span class="k">virtual</span> <span class="n">Monster</span><span class="o">*</span> <span class="n">spawnMonster</span><span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="k">new</span> <span class="n">T</span><span class="p">();</span> <span class="p">}</span>
<span class="p">};</span>
</pre></div>


<p>Using it looks like:</p>
<div class="codehilite"><pre><span class="n">Spawner</span><span class="o">*</span> <span class="n">ghostSpawner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SpawnerFor</span><span class="o">&lt;</span><span class="n">Ghost</span><span class="o">&gt;</span><span class="p">();</span>
</pre></div>


<aside name="base">

<p>The <code>Spawner</code> class here is so that code that doesn&#8217;t care what kind of monster
a spawner creates can just use it and work with pointers to <code>Monster</code>.</p>
<p>If we only had the <code>SpawnerFor&lt;T&gt;</code> class, there would be no single supertype the
instantiations of that template all shared, so any code that worked with
spawners of any monster type would itself need to take a template parameter.</p>
</aside>

<h3><a href="#first-class-types" name="first-class-types">First-class types</a></h3>
<p>The previous two solutions address the need to have a class, <code>Spawner</code>, which is
parameterized by a type. In C++, types aren&#8217;t generally first-class, so that
requires some <span name="type-obj">gymnastics</span>. If you&#8217;re using a
dynamically-typed language like JavaScript, Python, or Ruby where classes <em>are</em>
 regular objects you can pass around, you can solve this much more directly.</p>
<aside name="type-obj">

<p>In some ways, the <a href="type-object.html" class="pattern">Type Object</a>
pattern is another workaround for the lack of first-class types. That pattern
can still be useful even in languages with them, though, because it lets <em>you</em>
define what a &#8220;type&#8221; is. You may want different semantics than what the
language&#8217;s built-in classes provide.</p>
</aside>

<p>When you make a spawner, just pass in the class of monster that it should
construct&#8202;&mdash;&#8202;the actual runtime object that represents the monster&#8217;s
class. Easy as pie.</p>
<p>With all of these options, I honestly can&#8217;t say I&#8217;ve found a case where I felt
the Prototype <em>design pattern</em> was the best answer. Maybe your experience will
be different, but for now let&#8217;s put that away and talk about something else:
prototypes as a <em>language paradigm</em>.</p>
<h2><a href="#the-prototype-language-paradigm" name="the-prototype-language-paradigm">The Prototype Language Paradigm</a></h2>
<p>Many people think &#8220;object-oriented programming&#8221; is synonymous with &#8220;classes&#8221;.
Definitions of OOP tend to feel like credos of opposing religious denominations,
but a fairly non-contentious take on it is that <em>OOP lets you define &#8220;objects&#8221;
which bundle data and code together.</em> Compared to structured languages like C
and functional languages like Scheme, the defining characteristic of OOP is that
it tightly binds state and behavior together.</p>
<p>You may think classes are the one and only way to do that, but a handful of guys
including Dave Ungar and Randall Smith beg to differ. They created a language in
the 80s called Self. While as OOP as can be, it has no classes.</p>
<h3><a href="#self" name="self">Self</a></h3>
<p>In a pure sense, Self is <em>more</em> object-oriented than a class-based language. We
think of OOP as marrying state and behavior, but languages with classes actually
have a line of separation between them.</p>
<p>Consider the semantics of your favorite class-based language. To access some
state on an object, you look in the memory of the instance itself. State is
<em>contained</em> in the instance.</p>
<p>To invoke a <span name="vtable">method</span>, though, you look up the
instance&#8217;s class, and then you look up the method <em>there</em>. Behavior is contained
in the <em>class</em>. There&#8217;s always that level of indirection to get to a method,
which means fields and methods are different.</p>
<p><img src="images/prototype-class.png" alt="A Class contains a list of Methods. An Instance contains a list of Fields and a reference to its Class." /></p>
<aside name="vtable">

<p>For example, to invoke a virtual method in C++, you look in the instance for the
pointer to its vtable, then look up the method there.</p>
</aside>

<p>Self eliminates that distinction. To look up <em>anything</em>, you just look on the
object. An instance can contain both state and behavior. You can have a single
object that has a method completely unique to it.</p>
<p><span name="island"></span></p>
<p><img src="images/prototype-object.png" alt="An Object contains a mixed list of Fields and Methods." /></p>
<aside name="island">

<p>No man is an island, but this object is.</p>
</aside>

<p>If that was all Self did, it would be hard to use. Inheritance in class-based
languages, despite its faults, gives you a useful mechanism for reusing
polymorphic code and avoiding duplication. To accomplish something similar
without classes, Self has <em>delegation</em>.</p>
<p>To find a field or call a method on some object, we first look in the object
itself. If it has it, we&#8217;re done. If it doesn&#8217;t, we look at the object&#8217;s <span
name="parent"><em>parent</em></span>. This is just a reference to some other object.
When we fail to find a property on the first object, we try its parent, and its
parent, and so on. In other words, failed lookups are <em>delegated</em> to an object&#8217;s
parent.</p>
<aside name="parent">

<p>I&#8217;m simplifying here. Self actually supports multiple parents. Parents are just
specially marked fields, which means you can do things like inherit parents or
change them at runtime, leading to what&#8217;s called <em>dynamic inheritance</em>.</p>
</aside>

<p><img src="images/prototype-delegate.png" alt="An Object contains Fields and Methods and a reference to another object that it delegates to." /></p>
<p>Parent objects let us reuse behavior (and state!) across multiple objects, so
we&#8217;ve covered part of the utility of classes. The other key thing classes do is
give us a way to create instances. When you need a new thingamabob, you can just
do <code>new Thingamabob()</code>, or whatever your preferred language&#8217;s syntax is. A class
is a factory for instances of itself.</p>
<p>Without classes, how do we make new things? In particular, how do we make a
bunch of new things that all have stuff in common? Just like the design pattern,
the way you do this in Self is by <em>cloning</em>.</p>
<p>In Self, it&#8217;s as if <em>every</em> object supports the Prototype design pattern
automatically. Any object can be cloned. To make a bunch of similar objects, you:</p>
<ol>
<li>
<p>Beat one object into the shape you want. You can just clone the base <code>Object</code>
   built into the system and then stuff fields and methods into it.</p>
</li>
<li>
<p>Clone it to make as many&#8230; uh&#8230; clones as you want.</p>
</li>
</ol>
<p>This gives us the elegance of the Prototype design pattern without the tedium of
having to implement <code>clone()</code> ourselves; it&#8217;s built into the system.</p>
<p>This is such a beautiful, clever, minimal system that as soon as I learned about
it, <span name="finch">I started</span> creating a prototype-based language to get more experience with it.</p>
<aside name="finch">

<p>I realize building a language from scratch is not the most efficient way to
learn, but what can I say? I&#8217;m a bit peculiar. If you&#8217;re curious, the language
is called <a href="http://finch.stuffwithstuff.com/">Finch</a>.</p>
</aside>

<h3><a href="#how-did-it-go" name="how-did-it-go">How did it go?</a></h3>
<p>I was super excited to play with a pure prototype-based language, but once I had
mine up and running, I <span name="no-fun">discovered</span> an unpleasant fact:
it just wasn&#8217;t that fun to program in.</p>
<aside name="no-fun">

<p>I&#8217;ve since heard through the grapevine that many of the Self programmers came to
the same conclusion. The project was far from a loss, though. Self was so
dynamic that it needed all sorts of virtual machine innovations in order to run
fast enough.</p>
<p>The ideas they invented for just-in-time compilation, garbage collection, and
optimizing method dispatch are the exact same techniques&#8202;&mdash;&#8202;often implemented by
the same people!&#8202;&mdash;&#8202;that now make many of the world&#8217;s dynamically-typed
languages fast enough to use for massively popular applications.</p>
</aside>

<p>Sure, the language was simple to implement, but that was because it punted the
complexity onto the user. As soon as I started trying to use it, I found myself
missing the structure that classes give. I ended up trying to recapitulate it at
the library level since the language didn&#8217;t have it.</p>
<p>Maybe this is because my prior experience is in class-based languages, so
my mind has been tainted by that paradigm. But my hunch is that most people just
like well-defined &#8220;kinds of things&#8221;.</p>
<p>In addition to the runaway success of class-based languages, look at how many
games have explicit character classes and a precise roster of different sorts
of enemies, items, and skills, each neatly labeled. You don&#8217;t see many games
where each monster is a unique snowflake, like &#8220;sort of halfway between a troll
and a goblin with a bit of snake mixed in&#8221;.</p>
<p>While prototypes are a really cool paradigm and one that I wish more people
knew about, I&#8217;m glad that most of us aren&#8217;t actually programming using them
every day. <span name="telling">The code</span> I&#8217;ve seen that fully embraces
prototypes has a weird mushiness to it that I find hard to wrap my head around.</p>
<aside name="telling">

<p>It&#8217;s also telling how <em>little</em> code there actually is written in a prototypal
style. I&#8217;ve looked.</p>
</aside>

<h3><a href="#what-about-javascript" name="what-about-javascript">What about JavaScript?</a></h3>
<p>OK, if prototype-based languages are so unfriendly, how do I explain JavaScript?
Here&#8217;s a language with prototypes used by millions of people every day. More
computers run JavaScript than any other language on Earth.</p>
<p><span name="ten">Brendan Eich</span>, the creator of JavaScript, took
inspiration directly from Self, and many of JavaScript&#8217;s semantics are
prototype-based. Each object can have an arbitrary set of properties, both
fields and &#8220;methods&#8221; (which are really just functions stored as fields). An
object can also have another object, called its &#8220;prototype&#8221;, that it delegates
to if a field access fails.</p>
<aside name="ten">

<p>As a language designer, one appealing thing about prototypes is that they are
simpler to implement than classes. Eich took full advantage of this: the first
version of JavaScript was created in ten days.</p>
</aside>

<p>But, despite that, I believe that JavaScript in practice has more in common with
class-based languages than with prototypal ones. One hint that JavaScript has
taken steps away from Self is that the core operation in a prototype-based
language, <em>cloning</em>, is nowhere to be seen.</p>
<p>There is no method to clone an object in JavaScript. The closest it has is
<code>Object.create()</code>, which lets you create a new object that
delegates to an existing one. Even that wasn&#8217;t added until ECMAScript 5,
fourteen years after JavaScript came out. Instead of cloning, let me walk you
through the typical way you define types and create objects in JavaScript. You
start with a <em>constructor function</em>:</p>
<div class="codehilite"><pre><span class="kd">function</span> <span class="nx">Weapon</span><span class="p">(</span><span class="nx">range</span><span class="p">,</span> <span class="nx">damage</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">this</span><span class="p">.</span><span class="nx">range</span> <span class="o">=</span> <span class="nx">range</span><span class="p">;</span>
  <span class="k">this</span><span class="p">.</span><span class="nx">damage</span> <span class="o">=</span> <span class="nx">damage</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>


<p>This creates a new object and initializes its fields. You invoke it like:</p>
<div class="codehilite"><pre><span class="kd">var</span> <span class="nx">sword</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Weapon</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">16</span><span class="p">);</span>
</pre></div>


<p>The <code>new</code> here invokes the body of the <code>Weapon()</code> function with <code>this</code> bound to a
new empty object. The body adds a bunch of fields to it, then the now-filled-in
object is automatically returned.</p>
<p>The <code>new</code> also does one other thing for you. When it creates that blank object,
it wires it up to delegate to a prototype object. You can get to that object
directly using <code>Weapon.prototype</code>.</p>
<p>While state is added in the constructor body, to define <em>behavior</em>, you usually
add methods to the prototype object. Something like this:</p>
<div class="codehilite"><pre><span class="nx">Weapon</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">attack</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">target</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="nx">distanceTo</span><span class="p">(</span><span class="nx">target</span><span class="p">)</span> <span class="o">&gt;</span> <span class="k">this</span><span class="p">.</span><span class="nx">range</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;Out of range!&quot;</span><span class="p">);</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="nx">target</span><span class="p">.</span><span class="nx">health</span> <span class="o">-=</span> <span class="k">this</span><span class="p">.</span><span class="nx">damage</span><span class="p">;</span>
  <span class="p">}</span>
<span class="p">}</span>
</pre></div>


<p>This adds an <code>attack</code> property to the weapon prototype whose value is a
function. Since every object returned by <code>new Weapon()</code> delegates to
<code>Weapon.prototype</code>, you can now call <code>sword.attack()</code> and it will call that
function. It looks a bit like this:</p>
<p><img src="images/prototype-weapon.png" alt="A Weapon object contains an attack() method and other methods. A Sword object contains fields and delegates to Weapon." /></p>
<p>Let&#8217;s review:</p>
<ul>
<li>
<p>The way you create objects is by a &#8220;new&#8221; operation that you invoke using an
  object that represents the type&#8202;&mdash;&#8202;the constructor function.</p>
</li>
<li>
<p>State is stored on the instance itself.</p>
</li>
<li>
<p>Behavior goes through a level of indirection&#8202;&mdash;&#8202;delegating to the prototype &#8212;
  and is stored on a separate object that represents the set of methods shared
  by all objects of a certain type.</p>
</li>
</ul>
<p>Call me crazy, but that sounds a lot like my description of classes earlier. You
<em>can</em> write prototype-style code in JavaScript (<em>sans</em> cloning), but the syntax
and idioms of the language encourage a class-based approach.</p>
<p>Personally, I think that&#8217;s a <span name="good">good thing</span>. Like I said, I
find doubling down on prototypes makes code harder to work with, so I like that
JavaScript wraps the core semantics in something a little more classy.</p>
<h2><a href="#prototypes-for-data-modeling" name="prototypes-for-data-modeling">Prototypes for Data Modeling</a></h2>
<p>OK, I keep talking about things I <em>don&#8217;t</em> like prototypes for, which is making
this chapter a real downer. I think of this book as more comedy than tragedy, so
let&#8217;s close this out with an area where I <em>do</em> think prototypes, or more
specifically <em>delegation</em>, can be useful.</p>
<p>If you were to count all the bytes in a game that are code compared to the ones
that are data, you&#8217;d see the fraction of data has been increasing steadily since
the dawn of programming. Early games procedurally generated almost everything so
they could fit on floppies and old game cartridges. In many games today, the
code is just an &#8220;engine&#8221; that drives the game, which is defined entirely in
data.</p>
<p>That&#8217;s great, but pushing piles of content into data files doesn&#8217;t magically
solve the organizational challenges of a large project. If anything, it makes it
harder. The reason we use programming languages is because they have tools for
managing complexity.</p>
<p>Instead of copying and pasting a chunk of code in ten places, we move it into a
function that we can call by name. Instead of copying a method in a bunch of
classes, we can put it in a separate class that those classes inherit from or
mix in.</p>
<p>When your game&#8217;s data reaches a certain size, you really start wanting similar
features. Data modeling is a deep subject that I can&#8217;t hope to do justice here,
but I do want to throw out one feature for you to consider in your own games:
using prototypes and delegation for reusing data.</p>
<p>Let&#8217;s say we&#8217;re defining the data model for the <span name="shameless">shameless
Gauntlet rip-off</span> I mentioned earlier. The game designers need to specify
the attributes for monsters and items in some kind of files.</p>
<aside name="shameless">

<p>I mean completely original title in no way inspired by any previously existing
top-down multi-player dungeon crawl arcade games. Please don&#8217;t sue me.</p>
</aside>

<p>One common approach is to use JSON. Data entities are basically <em>maps</em>, or
<em>property bags</em>, or any of a dozen other terms because there&#8217;s nothing
programmers like more than <span name="inventing">inventing</span> a new name
for something that already has one.</p>
<aside name="inventing">

<p>We&#8217;ve re-invented them so many times that Steve Yegge calls them <a href="http://steve-yegge.blogspot.com/2008/10/universal-design-patter
n.html">&#8220;The Universal
Design Pattern&#8221;</a>.</p>
</aside>

<p>So a goblin in the game might be defined something like this:</p>
<div class="codehilite"><pre><span class="p">{</span>
  <span class="nt">&quot;name&quot;</span><span class="p">:</span> <span class="s2">&quot;goblin grunt&quot;</span><span class="p">,</span>
  <span class="nt">&quot;minHealth&quot;</span><span class="p">:</span> <span class="mi">20</span><span class="p">,</span>
  <span class="nt">&quot;maxHealth&quot;</span><span class="p">:</span> <span class="mi">30</span><span class="p">,</span>
  <span class="nt">&quot;resists&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;cold&quot;</span><span class="p">,</span> <span class="s2">&quot;poison&quot;</span><span class="p">],</span>
  <span class="nt">&quot;weaknesses&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;fire&quot;</span><span class="p">,</span> <span class="s2">&quot;light&quot;</span><span class="p">]</span>
<span class="p">}</span>
</pre></div>


<p>This is pretty straightforward and even the most text-averse designer can handle
that. So you throw in a couple of sibling branches on the Great Goblin Family
Tree:</p>
<div class="codehilite"><pre><span class="p">{</span>
  <span class="nt">&quot;name&quot;</span><span class="p">:</span> <span class="s2">&quot;goblin wizard&quot;</span><span class="p">,</span>
  <span class="nt">&quot;minHealth&quot;</span><span class="p">:</span> <span class="mi">20</span><span class="p">,</span>
  <span class="nt">&quot;maxHealth&quot;</span><span class="p">:</span> <span class="mi">30</span><span class="p">,</span>
  <span class="nt">&quot;resists&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;cold&quot;</span><span class="p">,</span> <span class="s2">&quot;poison&quot;</span><span class="p">],</span>
  <span class="nt">&quot;weaknesses&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;fire&quot;</span><span class="p">,</span> <span class="s2">&quot;light&quot;</span><span class="p">],</span>
  <span class="nt">&quot;spells&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;fire ball&quot;</span><span class="p">,</span> <span class="s2">&quot;lightning bolt&quot;</span><span class="p">]</span>
<span class="p">}</span>

<span class="p">{</span>
  <span class="nt">&quot;name&quot;</span><span class="p">:</span> <span class="s2">&quot;goblin archer&quot;</span><span class="p">,</span>
  <span class="nt">&quot;minHealth&quot;</span><span class="p">:</span> <span class="mi">20</span><span class="p">,</span>
  <span class="nt">&quot;maxHealth&quot;</span><span class="p">:</span> <span class="mi">30</span><span class="p">,</span>
  <span class="nt">&quot;resists&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;cold&quot;</span><span class="p">,</span> <span class="s2">&quot;poison&quot;</span><span class="p">],</span>
  <span class="nt">&quot;weaknesses&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;fire&quot;</span><span class="p">,</span> <span class="s2">&quot;light&quot;</span><span class="p">],</span>
  <span class="nt">&quot;attacks&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;short bow&quot;</span><span class="p">]</span>
<span class="p">}</span>
</pre></div>


<p>Now, if this was code, our aesthetic sense would be tingling. There&#8217;s a lot of
duplication between these entities, and well-trained programmers <em>hate</em> that. It
wastes space and takes more time to author. You have to read carefully to tell
if the data even <em>is</em> the same. It&#8217;s a maintenance headache. If we decide to
make all of the goblins in the game stronger, we need to remember to update the
health of all three of them. Bad bad bad.</p>
<p>If this was code, we&#8217;d create an abstraction for a &#8220;goblin&#8221; and reuse that
across the three goblin types. But dumb JSON doesn&#8217;t know anything about that.
So let&#8217;s make it a bit smarter.</p>
<p>We&#8217;ll declare that if an object has a <span name="meta"><code>"prototype"</code></span>
field, then that defines the name of another object that this one delegates to.
Any properties that don&#8217;t exist on the first object fall back to being looked up
on the prototype.</p>
<aside name="meta">

<p>This makes the <code>"prototype"</code> a piece of <em>meta</em>data instead of data. Goblins have
warty green skin and yellow teeth. They don&#8217;t have prototypes. Prototypes are a
property of the <em>data object representing the goblin</em>, and not the goblin
itself.</p>
</aside>

<p>With that, we can simplify the JSON for our goblin horde:</p>
<div class="codehilite"><pre><span class="p">{</span>
  <span class="nt">&quot;name&quot;</span><span class="p">:</span> <span class="s2">&quot;goblin grunt&quot;</span><span class="p">,</span>
  <span class="nt">&quot;minHealth&quot;</span><span class="p">:</span> <span class="mi">20</span><span class="p">,</span>
  <span class="nt">&quot;maxHealth&quot;</span><span class="p">:</span> <span class="mi">30</span><span class="p">,</span>
  <span class="nt">&quot;resists&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;cold&quot;</span><span class="p">,</span> <span class="s2">&quot;poison&quot;</span><span class="p">],</span>
  <span class="nt">&quot;weaknesses&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;fire&quot;</span><span class="p">,</span> <span class="s2">&quot;light&quot;</span><span class="p">]</span>
<span class="p">}</span>

<span class="p">{</span>
  <span class="nt">&quot;name&quot;</span><span class="p">:</span> <span class="s2">&quot;goblin wizard&quot;</span><span class="p">,</span>
  <span class="nt">&quot;prototype&quot;</span><span class="p">:</span> <span class="s2">&quot;goblin grunt&quot;</span><span class="p">,</span>
  <span class="nt">&quot;spells&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;fire ball&quot;</span><span class="p">,</span> <span class="s2">&quot;lightning bolt&quot;</span><span class="p">]</span>
<span class="p">}</span>

<span class="p">{</span>
  <span class="nt">&quot;name&quot;</span><span class="p">:</span> <span class="s2">&quot;goblin archer&quot;</span><span class="p">,</span>
  <span class="nt">&quot;prototype&quot;</span><span class="p">:</span> <span class="s2">&quot;goblin grunt&quot;</span><span class="p">,</span>
  <span class="nt">&quot;attacks&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;short bow&quot;</span><span class="p">]</span>
<span class="p">}</span>
</pre></div>


<p>Since the archer and wizard have the grunt as their prototype, we don&#8217;t have to
repeat the health, resists, and weaknesses in each of them. The logic we&#8217;ve added
to our data model is super simple&#8202;&mdash;&#8202;basic single delegation&#8202;&mdash;&#8202;but we&#8217;ve
already gotten rid of a bunch of duplication.</p>
<p>One interesting thing to note here is that we didn&#8217;t set up a fourth &#8220;base
goblin&#8221; <em>abstract</em> prototype for the three concrete goblin types to delegate to.
Instead, we just picked one of the goblins who was the simplest and delegated to
it.</p>
<p>That feels natural in a prototype-based system where any object can be used as a
clone to create new refined objects, and I think it&#8217;s equally natural here too.
It&#8217;s a particularly good fit for data in games where you often have one-off
special entities in the game world.</p>
<p>Think about bosses and unique items. These are often refinements of a more
common object in the game, and prototypal delegation is a good fit for defining
those. The magic Sword of Head-Detaching, which is really just a longsword with
some bonuses, can be expressed as that directly:</p>
<div class="codehilite"><pre><span class="p">{</span>
  <span class="nt">&quot;name&quot;</span><span class="p">:</span> <span class="s2">&quot;Sword of Head-Detaching&quot;</span><span class="p">,</span>
  <span class="nt">&quot;prototype&quot;</span><span class="p">:</span> <span class="s2">&quot;longsword&quot;</span><span class="p">,</span>
  <span class="nt">&quot;damageBonus&quot;</span><span class="p">:</span> <span class="s2">&quot;20&quot;</span>
<span class="p">}</span>
</pre></div>


<p>A little extra power in your game engine&#8217;s data modeling system can make it
easier for designers to add lots of little variations to the armaments and
beasties populating your game world, and that richness is exactly what delights
players.</p>
<nav>
  <span class="prev">&larr; <a href="observer.html">Previous Chapter</a></span>
  <span class="next"><a href="singleton.html">Next Chapter</a> &rarr;</span>
  <span class="toc">&equiv; <a href="/">The Book</a></span>
</nav>
</div>
</div>
<footer>&copy; 2009-2014 Robert Nystrom</footer>
</body>
</html>
